﻿using System;
using System.Linq;
using System.Windows;
using Tanis.ViewModels;
using Tanis.Controls;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Coding4Fun.Phone.Controls;
using System.Collections.Generic;
using Tanis.Settings;

namespace Tanis
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            Loaded += MainPage_Loaded;

            _pivot.Title = SettingsControl.DefaultCity.ToUpper();
            App.ViewModel.SearchPerfoming += ViewModelOnSearchPerforming;

            UpdatePanelVisibility();

        	App.ViewModel.SearchPerfomed += ViewModelOnSearchPerfomed;
			App.ViewModel.DetailsRequested += OnDetailsRequested;
            App.ViewModel.DataLoaded += ViewModel_DataLoaded;

            _loadingIndicator = new ProgressIndicator();
            _loadingIndicator.IsVisible = false;
            _loadingIndicator.IsIndeterminate = true;
            _loadingIndicator.Text = "Loading ...";

            SystemTray.SetProgressIndicator(this, _loadingIndicator);

            MainPageInstance = this;
        }

        void ViewModel_DataLoaded(object sender, EventArgs e)
        {
            _loadingIndicator.IsVisible = false;
        }

        #region Shortcuts for easy access

        public static MainPage MainPageInstance { get; private set; }
        public RouteDetailsControl RouteDetails
        {
            get
            {
                return _routeDetailsCtrl;
            }
        }

        public RouteFinderControl RouteFinder
        {
            get
            {
                return _routeFinderCtrl.Content as RouteFinderControl;
            }
        }

        public FavoritesControl Favourites
        {
            get
            {
                return _favouriteRouteCtrl.Content as FavoritesControl;
            }
        }

        public RouteList RouteList
        {
            get
            {
                return _routeListCtrl.Content as RouteList;
            }
        }

        #endregion

        private ProgressIndicator _loadingIndicator;

        private void OnDetailsRequested(object sender, DetailsRequestedArgs detailsRequestedArgs)
    	{
    		_routeDetailsCtrl.RouteSummary = detailsRequestedArgs.RouteSummary;
            _pivot.SelectedItem = _routeDetailsPivotPage;
    	}

        private void ViewModelOnSearchPerforming(object sender, EventArgs eventArgs)
        {
            
        }

    	private void ViewModelOnSearchPerfomed(object sender, EventArgs eventArgs)
    	{
            _pivot.SelectedItem = _routeListCtrl;
    	}

        // Load data for the ViewModel Routes
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                _loadingIndicator.IsVisible = true;
            }

            if (SettingsControl.GetApplicationSetting("tutorial") == null)
            {
                NavigationService.Navigate(new Uri("/Settings/TutorialPage.xaml", UriKind.Relative));
            }
        }

        /// <summary>
        /// Settings button clicked event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnSettingsClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Settings/SettingsPage.xaml", UriKind.Relative));
        }

        /// <summary>
        /// "Add to favourites" button clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddToFavouritesButton_Click(object sender, EventArgs e)
        {
            InputPrompt input = new InputPrompt();
            input.Completed +=new EventHandler<PopUpEventArgs<string,PopUpResult>>(input_Completed);

            input.Title = Localization.LocalizedStringsRes.AddToFavouritesDialogTitle;
            input.Message = Localization.LocalizedStringsRes.AddToFavouritesDialogText;
            input.IsCancelVisible = true;

            // get suggested name for dialog //
            RouteQuery query = RouteFinder.GetRouteQuery();
            input.Value = query.DefaultName;
            
            input.Show();            
        }

        /// <summary>
        /// User completes "add to favourites" dialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void input_Completed(object sender, PopUpEventArgs<string, PopUpResult> e)
        {
            if (e.PopUpResult == PopUpResult.Cancelled)
            {
                return;
            }

            // check if valid name entered //
            if (e.Result == String.Empty)
            {
                AddToFavouritesButton_Click(sender, null);
                return;
            }

            if (Favourites.ContainsRoute(e.Result))
            {
                // route name already exists in favourites //
                MessageBox.Show(Localization.LocalizedStringsRes.FavouriteRouteAlreadyExistsMessage, Localization.LocalizedStringsRes.WarningTitle, MessageBoxButton.OK);
                return;
            }

            // save the added favourite in phone memory //
            RouteQuery query = RouteFinder.GetRouteQuery();
            query.Name = e.Result.ToString();
            Favourites.AddFavouriteRoute(query);
        }

        /// <summary>
        /// Event handler for when user slides left/right in panorama view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _pivot_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (ApplicationBar == null)
            {
                return;
            }

            PivotItem newItem = e.AddedItems[0] as PivotItem;
            string buttonName = null;

            switch (newItem.Name)
            {
                case "_routeFinderCtrl":
                    {
                        buttonName = Localization.LocalizedStringsRes.SearchButton;
                    } break;
                case "_routeListCtrl":
                case "_routeDetailsCtrl":
                    {
                        if (!RouteFinder.FavouriteSearchPerformed)
                        {
                            buttonName = Localization.LocalizedStringsRes.SaveFavouriteRouteButtonText;
                        }                        
                    } break;
            }

            UpdateButtons(buttonName);
        }

        private void UpdateButtons(string buttonName)
        {
            if (ApplicationBar.Buttons.Cast<ApplicationBarIconButton>().Any(x => x.Text == buttonName))
            {
                return;
            }

            ApplicationBar.Buttons.Clear();

            if (!String.IsNullOrEmpty(buttonName))
            {
                // create new button //
                var newButton = new ApplicationBarIconButton();
                newButton.Text = buttonName;

                if (buttonName == Localization.LocalizedStringsRes.SaveFavouriteRouteButtonText)
                {
                    newButton.IconUri = new Uri("/Images/appbar.save.rest.png", UriKind.Relative);
                    newButton.Click += new EventHandler(AddToFavouritesButton_Click);
                }

                if (buttonName == Localization.LocalizedStringsRes.SearchButton)
                {
                    newButton.IconUri = new Uri("/Images/appbar.feature.search.rest.png", UriKind.Relative);
                    newButton.Click += new EventHandler(RouteFinder.OnSearchBtnClick);
                }

                ApplicationBar.Buttons.Insert(0, newButton);
            }

        }

        public void UpdatePanelVisibility()
        {
            // if search was not performed hide route list and route details //
            if (!RouteFinder.SearchPerformed)
            {
                HidePivotItem(_routeListCtrl);
                HidePivotItem(_routeDetailsPivotPage);
            }
            else
            {
                ShowPivotItem(_routeListCtrl, 2);
                ShowPivotItem(_routeDetailsPivotPage, 3);
            }

            // if search was performed but details have not been requested, hide details page //
            if (!RouteFinder.RouteDetailsRequested)
            {
                HidePivotItem(_routeDetailsPivotPage);
            }
            else
            {
                ShowPivotItem(_routeDetailsPivotPage, 3);
            }

            // if there are no favourite routes, hide them //
            if (Favourites.FavouriteRouteList.Count == 0)
            {
                HidePivotItem(_favouriteRouteCtrl);
            }
            else
            {
                ShowPivotItem(_favouriteRouteCtrl, 0);
            }
        }

        private void ShowPivotItem(PivotItem pivotItem, int position)
        {
            if (!_pivot.Items.Contains(pivotItem))
            {
                _pivot.Items.Insert(Math.Min(position, _pivot.Items.Count), pivotItem);
            }
        }

        private void HidePivotItem(PivotItem pivotItem)
        {
            if (_pivot.Items.Contains(pivotItem))
            {
                _pivot.Items.Remove(pivotItem);
            }
        }

        /// <summary>
        /// Controls "back" button behaviour for main pivot
        /// </summary>
        /// <param name="e"></param>
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);

            if (_pivot.SelectedItem == _routeListCtrl)
            {
                e.Cancel = true;
                _pivot.SelectedItem = _routeFinderCtrl;                
            }

            if (_pivot.SelectedItem == _routeDetailsPivotPage)
            {
                e.Cancel = true;
                _pivot.SelectedItem = _routeListCtrl;
            }
        }
    }
}